#!/usr/bin/env node
const readline=require('readline');
const { inputVerify, isNumber } = require('./utils/inputVerify');
const { calculateEntropy } = require('./utils/calculateEntropy');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
}); 

rl.on('close',()=>{
    console.log('\n');
    process.exit(0);
})  

const promptForProbs=()=>{
    console.log('请输入信源概率分布：(Ctrl+D退出输入)');
    let probs = [];
    let index=0;
    const requestProb=()=>{
        rl.question(`p${index}:`,(answer)=>{
            if(answer.trim()===''){
                if(probs.length===0){
                    console.log('命令行参数错误：参数数量小于1个');
                    requestProb();
                    return;
                }
                processProbs(probs);
                return;
            }
            if(!isNumber(answer)){
                console.log('请输入数字！');
                requestProb();
                return;
            }
            const prob=parseFloat(answer);
            if(prob<0){
                console.log('请输入大于0的数字！');
                requestProb();
                return;
            }
            if(prob>1){
                console.log('请输入小于1的数字！');
                requestProb();
                return; 
            }
            probs.push(prob);
            const sum = probs.reduce((acc,cur)=>acc+cur,0);
            if(Math.abs(sum-1)<1e-6){
                const entropy=calculateEntropy(probs);
                console.log(`p=[${probs.join(', ')}]`);
                console.log(`h(p)=${entropy} bit`);
                rl.close();
                return; 
            }else if(sum>1){
                console.log('概率空间不封闭，概率之和大于1');
                probs=[];
                index=0;
                console.log('请输入信源概率分布：(Ctrl+D退出输入)');
                requestProb();
                return;
            }
            index++;
            requestProb();
        })
    }
    requestProb();
}

const processProbs=(probs)=>{
    const result = inputVerify(probs);
    if(result!==true){
        console.log(result);
        promptForProbs();
        return;
    }

    const entropy = calculateEntropy(probs);
    console.log(`p=[${probs.join(', ')}]`);
    console.log(`h(p)=${entropy} bit`);
    rl.close();
}

const parseArgs = () => {
    const args = process.argv.slice(2);
    if(args.length===0){
        console.log('命令行参数错误：参数数量小于1个');
        return null;
    }
    let probs;
    const fullInput = args.join(' ');
    if(fullInput.includes(',')&& fullInput.includes(' ')){
        console.log('命令行参数错误：不允许同时使用逗号和空格分隔概率值！');
        return null;
    }
    if(fullInput.includes(',')){
        probs = fullInput.split(',').map(parseFloat);
    }else{
        probs=args.map(parseFloat);
    }
    if(probs.some(isNaN)){
        console.log('请输入数字！');
        return null;    
    }
    return probs;
}

const commandLineProbabilities=parseArgs();
if(commandLineProbabilities){
    processProbs(commandLineProbabilities);
}else{
    promptForProbs();
}

